package netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.InetSocketAddress;
import java.util.Random;

public class HelloWorldClient {
    static Logger logger = LogManager.getLogger("mylog");
    public static void main(String[] args) throws InterruptedException {
        send();
        System.out.println("fished");
    }

    private static byte[] fill10Bytes(char c, int len) {
        if (len < 0 || len > 10) {
            System.out.println("fill 10 bytes error, len invaild");
        }
        byte[] re = new byte[10];
        for (int i = 0; i < len; i++) {
            re[i] = (byte)c;
        }
        for (int i = len; i < 10; i++) {
            re[i] = '_';
        }
        return re;
    }

    private static StringBuilder makeString(char c, int len) {
        StringBuilder sb = new StringBuilder(len + 2);
        for (int i = 0; i < len; i++) {
            sb.append(c);
        }
        sb.append('\n');
        return sb;
    }

    private static void send() {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(worker)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {

                        @Override
                        protected void initChannel(NioSocketChannel nioSocketChannel){
                            nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    logger.debug("sending...");
                                    ByteBuf buf = ctx.alloc().buffer(16);
                                    Random r = new Random();
                                    char c = '0';
                                    for (int i = 0; i < 10; i++) {
                                       // byte[] bytes = fill10Bytes(c, r.nextInt(10) + 1);
                                        StringBuilder sb = makeString(c, r.nextInt(200));
                                        buf.writeBytes(sb.toString().getBytes());
                                        c++;
                                    }
                                    ctx.writeAndFlush(buf);
                                }
                            });
                        }
                    });
                    ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync();
                    channelFuture.channel().closeFuture().sync();
        }catch (InterruptedException e) {
            logger.error("client error{}", e);
        }finally {
            worker.shutdownGracefully();
        }
    }
}
